﻿using OperationPlugins.Mvc.Filters;
using System.Web.Mvc;
using TimeProject.Engine;
using TimeProject.Engine.DbContent;
using TimeProject.Engine.DbModels;
using TimeProject.Engine.Providers;
using TimeProject.WebSite.ViewModels;

namespace TimeProject.WebSite.Controllers
{
    public partial class TimeProjectController
    {
        [HttpGet]
        [CurrentOperation(TimeProjectOperations.MyAccount)]
        public ActionResult MyAccount()
        {
            MyAccountViewModel vm = new MyAccountViewModel();

            User user = Db.GetUser(UserId);

            vm.PublicId = EntityPublicIdProvider.GetPublicId(user);
            vm.Username = user.Username;
            vm.FullName = user.FullName;
            vm.EMail = user.EMail;

            foreach (IUserOptionProvider userOptionProvider in UserOptionProviders)
            {
                foreach (BooleanUserOptionDefinition definition in userOptionProvider.GetBooleanUserOptionDefinitions())
                {
                    UserOption option = Db.GetUserOption(UserId, definition.Key);

                    UserOptionViewModel optionVm = new UserOptionViewModel
                    {
                        IsBooleanOption = true,
                        Key = definition.Key,
                        Title = definition.Title,
                        BooleanValue = option != null && option.BooleanValue
                    };

                    vm.UserOptions.Add(optionVm);
                }
            }

            return View(vm);
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.MyAccount)]
        public ActionResult MyAccount(MyAccountViewModel vm)
        {
            return Json(vm, () =>
            {
                User user = Db.GetUser(UserId);

                user.FullName = vm.FullName;
                user.EMail = vm.EMail;

                foreach (UserOptionViewModel optionVm in vm.UserOptions)
                {
                    UserOption option = Db.GetUserOption(UserId, optionVm.Key);

                    if (option == null)
                    {
                        Db.UserOptions.Add(new UserOption
                        {
                            UserId = UserId,
                            Key = optionVm.Key,
                            BooleanValue = optionVm.BooleanValue
                        });
                    }
                    else
                    {
                        option.BooleanValue = optionVm.BooleanValue;
                    }
                }

                if (SaveDbContext(vm))
                {
                    vm.RedirectTo("Index");
                }
            });
        }

    }
}